import {defineStore} from 'pinia'
import {
    refreshToken,
    weiXinMiniAppLogin,
    weiXinMiniAppPhoneLogin
} from "@/api/auth/auth";
import {clone} from 'lodash'
import {getUserInfo} from "@/api/user";
import {getRefreshToken} from "@/utils/auth";
import {bindInviteeCode} from "@/api/invention";
import {getInviteeCode} from "@/utils/invite";
import {PayWalletApi} from "@/api/pay/wallet";
import type {PayWallet} from "@/types/pay";

const staticUrl = import.meta.env.VITE_STATIC_URL

/**
 * 默认用户信息
 */
export const defaultUserInfo: UserInfo | undefined = {
    avatar: `${staticUrl}/user-default-avatar.png`,
    brokerageEnabled: false,
    experience: 0,
    id: 0,
    level: "",
    mobile: "",
    nickname: "登录/注册",
    point: 0,
    sex: 0
}

export const user = defineStore('member', {

    state: () => ({
        // 用户基本信息
        userInfo: clone<UserInfo>(defaultUserInfo),
        // 用户支付钱包
        payWallet: clone<PayWallet>({})
    }),

    actions: {

        // 微信小程序快捷登录
        async login() {
            let {code} = await uni.login()
            if (!code) throw new Error("微信登录授权失败")
            return weiXinMiniAppLogin(code, "default", 34)
        },

        // 微信小程序手机号码快捷登录
        async phoneLogin(phoneCode: string) {
            let {code} = await uni.login()
            if (!code) throw new Error("微信登录授权失败")
            let {data} = await weiXinMiniAppPhoneLogin(phoneCode, code, "default")
            // 如果有被邀请码的缓存，说明通过扫码进入，尝试绑定
            if (getInviteeCode()) await bindInviteeCode(getInviteeCode())
            return data ? Promise.resolve(data) : Promise.reject(data)
        },

        // 获取用户基本信息
        async getUserInfo() {
            let {data} = await getUserInfo()
            if (!data?.mobile) await uni.reLaunch({url: '/pages/login/index'})
            return Promise.resolve(this.userInfo = <UserInfo>data)
        },

        // token 刷新
        async refreshToken() {
            return await refreshToken(getRefreshToken())
        },

        // 钱包信息
        async getPayWallet() {
            let {data} = await PayWalletApi.getPayWallet()
            this.payWallet = clone<PayWallet>(data)
            return Promise.resolve(data)
        }

    }

})
